<template>
  <div class="line-echart">
    <base-chart
      :id="`chartsMax${chartKey}`"
      :options="state.options"
      :height="height"
      class="chartsMax"
      @onload="handleEchartsInit"
    />
  </div>
</template>

<script setup>
import BaseChart from '@/base-ui/echart/base-chart.vue'
import { computed, reactive, watch } from 'vue'
import emitter from '@/utils/bus'
const props = defineProps({
  chartKey: {
    type: String,
    default: ''
  },
  height: {
    type: String,
    default: ''
  },
  title: {
    type: String,
    default: ''
  },
  xLabels: {
    type: Array,
    default: () => []
  },
  servers: {
    type: Array,
    default: () => []
  },
  znData: {
    type: Array,
    default: () => []
  }
})
const state = reactive({
  // 预报流量
  forecastFlow: [],
  symbolsArr: [
    'M5,0 A5,3 0 1 1 4.8,0 Z', // 类似椭圆的一部分
    'M2,5 Q5,2 8,5 T10,5', // 二次贝塞尔曲线形成的弧形
    'M5,0 C3,3 7,3 5,6 Z', // 三次贝塞尔曲线形成的类似拱形
    'M0,5 A5,5 0 0 1 10,5', // 半圆
    'M3,3 A3,3 0 1 0 7,3', // 四分之一圆
    'M0,0 L10,0 L10,10 L0,10 Z M2,2 L8,2 L8,8 L2,8 Z M4,4 L6,4 L6,6 L4,6 Z', // 大正方形套中正方形套小正方形
    'M0,0 L5,10 L10,0 Z M2,4 L3,6 L4,4 Z', // 三角形内嵌套小三角形
    'M0,5 L5,0 L10,5 L5,10 Z M3,3 L7,3 L7,7 L3,7 Z M4,4 L6,4 L6,6 L4,6 Z', // 菱形内套正方形套更小正方形
    'M2,0 L8,0 L10,5 L8,10 L2,10 L0,5 Z M4,3 L6,3 L6,7 L4,7 Z M5,4 L5,6 Z', // 椭圆内套矩形套线段
    'M5,0 A5,4 0 1 1 4.9,0 Z M3,2 L7,2 L7,6 L3,6 Z', // 椭圆弧内套矩形
    'M0,0 L3,5 L6,0 L9,5 L12,0 Z', // 五边形变形
    'M1,1 L4,4 L7,1 L10,4 L13,1 Z', // 另一种五边形变形
    'M0,0 L2,6 L4,0 L6,6 L8,0 L10,6 Z', // 六边形变形
    'M3,0 L6,4 L9,0 L12,4 L15,0 L12,-4 L9,0 L6,-4 Z', // 八边形变形
    'M1,3 L4,7 L7,3 L10,7 L13,3 Z', // 不规则五边形
    'M0,5 L5,0 L10,5 L5,10 Z', // 菱形
    'M2,5 L5,2 L8,5 L5,8 Z', // 较小的菱形
    'M0,0 L4,4 L4,10 L0,6 Z', // 平行四边形
    'M5,0 L10,3 L10,7 L5,10 L0,7 L0,3 Z', // 五边形
    'M5,0 A5,4 0 1 1 4.9,0 Z',
    'M4,0 L5,0 L5,5 L0,10 Z',
    'M4,0 L5,0 L5,10 L0,10 Z',
    'M0,0 L0,10 L10,10 L10,0 Z', // 方形
    'M0,0 L5,10 L10,0 Z', // 三角形
    'M0,0 L5,10 L10,10 L10,0 L0,0 Z', // 外部带孔的方形
    'M2,0 L8,0 L10,5 L8,10 L2,10 L0,5 Z' // 园
  ],
  options: {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
      }
    },

    legend: [
      {
        selected: {
          警戒水位: false
        },
        top: 10,
        data: [],
        itemGap: 20,
        type: 'scroll',
        orient: 'horizontal'
      },
      {
        top: 30,
        data: [],
        type: 'scroll',
        orient: 'horizontal',
        width: 960
      }
    ],
    grid: [
      { x: '8%', y: '20%', height: '25%', top: '20%', right: 100 },
      { x: '8%', y2: '15%', height: '30%', top: '50%', right: 100 }
    ],
    //多个图，就要定义多个x轴，虽然我这个表的x轴是一样的
    xAxis: [
      {
        show: false, //隐藏了x轴
        type: 'category',
        gridIndex: 0, //对应前面grid的索引位置（第一个）
        axisTick: {
          alignWithLabel: true
        },
        // axisLabel: {
        //   interval: 6 //x轴显示的数量，我这里是动态算的
        // },
        data: props.xLabels
      },
      {
        show: true,
        type: 'category',
        min: '0',
        max: '1000',
        splitLine: {
          show: true
        },
        axisTick: {
          alignWithLabel: true
        },
        gridIndex: 1, //对应前面grid的索引位置（第二个）
        //   axisLabel:{
        //     interval:1,
        // },
        data: props.xLabels,
        boundaryGap: false
      }
    ],
    //y轴，不管有几个x轴，几个y轴，或者图，只要找到他对应的grid图的序号索引就可以精准匹配
    yAxis: [
      {
        type: 'value',
        gridIndex: 1, //对应前面grid的索引位置（第二个）
        name: '流量',
        nameLocation: 'middle',
        position: 'right',
        splitNumber: 3,
        axisLine: {
          show: true,
          lineStyle: {
            color: '#000'
          }
        },
        nameTextStyle: {
          padding: [15, 0, 0, 0]
        },
        axisLabel: {
          formatter: '{value}'
        }
      },
      {
        type: 'value',
        gridIndex: 1,
        nameLocation: 'middle',
        name: '水位',
        splitNumber: 5,
        position: 'left',
        axisLine: {
          show: true,
          lineStyle: {
            color: '#000'
          }
        },
        nameTextStyle: {
          padding: [0, 0, 10, 0]
        },
        axisLabel: {
          formatter: '{value}',
          showMaxLabel: false
        }
      },
      {
        type: 'value',
        gridIndex: 0,
        name: '降雨量',
        position: 'left',
        splitNumber: 3,
        nameLocation: 'middle', //y轴name的位置
        inverse: true,

        axisLine: {
          show: true,
          lineStyle: {
            color: '#000'
          }
        },
        nameTextStyle: {
          padding: [0, 0, 10, 0]
        },
        axisLabel: {
          formatter: '{value}',
          textStyle: {
            fontSize: 12 //y轴坐标轴上的字体大小
          }
        }
      },
      {
        type: 'value',
        gridIndex: 0,
        name: '',
        position: 'right',
        splitNumber: 3,
        nameLocation: 'middle', //y轴name的位置
        inverse: true,
        axisLine: {
          show: true,
          lineStyle: {
            color: '#000'
          }
        },
        nameTextStyle: {
          padding: [0, 0, 10, 0]
        },
        axisLabel: {
          formatter: '{value}',
          textStyle: {
            fontSize: 12 //y轴坐标轴上的字体大小
          }
        }
      }
    ],

    //数据就要选择是哪个x,y轴与之对应
    series: [],
    dataZoom: [
      {
        type: 'slider',
        show: true,
        height: 20,
        bottom: 20,
        startValue: props.servers[0]?.fcTime || '0',
        // start: 0,
        // end: 100,
        xAxisIndex: [0, 1]
      },
      {
        type: 'inside',
        xAxisIndex: [0, 1]
      }
    ],
    toolbox: {
      //
      top: '25',
      right: '15',
      show: true,
      feature: {
        myFull: {
          show: true,
          title: '全屏查看',
          icon: 'path://M432.45,595.444c0,2.177-4.661,6.82-11.305,6.82c-6.475,0-11.306-4.567-11.306-6.82s4.852-6.812,11.306-6.812C427.841,588.632,432.452,593.191,432.45,595.444L432.45,595.444z M421.155,589.876c-3.009,0-5.448,2.495-5.448,5.572s2.439,5.572,5.448,5.572c3.01,0,5.449-2.495,5.449-5.572C426.604,592.371,424.165,589.876,421.155,589.876L421.155,589.876z M421.146,591.891c-1.916,0-3.47,1.589-3.47,3.549c0,1.959,1.554,3.548,3.47,3.548s3.469-1.589,3.469-3.548C424.614,593.479,423.062,591.891,421.146,591.891L421.146,591.891zM421.146,591.891',
          onclick: () => {
            // this.fullFlag = true;
            let element = document.getElementById(`chartsMax${props.chartKey}`)

            // 一些浏览器的兼容性
            if (element.requestFullScreen) {
              // HTML W3C 提议
              element.requestFullScreen()
            } else if (element.msRequestFullscreen) {
              // IE11
              element.msRequestFullScreen()
            } else if (element.webkitRequestFullScreen) {
              // Webkit (works in Safari5.1 and Chrome 15)
              element.webkitRequestFullScreen()
            } else if (element.mozRequestFullScreen) {
              // Firefox (works in nightly)
              element.mozRequestFullScreen()
            }

            // 退出全屏
            if (element.requestFullScreen) {
              document.exitFullscreen()
            } else if (element.msRequestFullScreen) {
              document.msExitFullscreen()
            } else if (element.webkitRequestFullScreen) {
              document.webkitCancelFullScreen()
            } else if (element.mozRequestFullScreen) {
              document.mozCancelFullScreen()
            }
          }
        }
      }
    }
  }
})
const handleEchartsInit = (echartInst) => {
  // 监听图例选中状态变化事件
  echartInst.on('legendselectchanged', (params) => {
    if (params.name.indexOf(':') === -1) {
      for (let key in params.selected) {
        if (key.indexOf(':') !== -1 && key.indexOf(params.name) !== -1) {
          // 模型工程选中，对应的预报水位和预报流量也选中
          if (params.selected[params.name]) {
            echartInstance.value.dispatchAction({
              type: 'legendSelect',
              name: key
            })
          } else {
            echartInstance.value.dispatchAction({
              type: 'legendUnSelect',
              name: key
            })
          }
        }
      }
    }
  })
}
watch(
  () => {
    props.znData
  },
  () => {
    if (props.znData?.length) {
      state.forecastFlow = props.znData?.map((child, childIndex) => {
        return child.fq
      })
      state.forecastTime = props.znData?.map((child, childIndex) => {
        return child.tm
      })
      if (props.servers.length) {
        for (let index = -1; index < state.options.xAxis[0].data.length; index++) {
          const element = state.options.xAxis[0].data[index]
          if (element === props.servers[0].fcTime || props.servers[0].fcTime == undefined) {
            break
          } else {
            state.forecastFlow.unshift(null)
          }
        }
      } else {
        state.options.xAxis[1].data = state.forecastTime
      }
      state.options.legend[0].data.push({
        name: '智能水文预报',
        itemStyle: { opacity: 0 }
      })
      state.options.series.push({
        type: 'line',
        symbolSize: 0,
        name: '智能水文预报',
        lineStyle: {
          // type: 'solid'
          // color: '#3cf40bff'
          color: '#000'
        },
        smooth: true,
        symbol: 'circle',
        showSymbol: false,
        xAxisIndex: 1,
        yAxisIndex: 0,
        data: state.forecastFlow || ''

        // data:[12,54,234,321,78,43]
      })
      console.log('666', state.forecastFlow)
    } else {
      state.options.legend[0].data = state.options.legend[0].data.filter((item) => {
        return item.name != '智能水文预报'
      })

      state.options.series = state.options.series.filter((item) => {
        return item.name != '智能水文预报'
      })
      state.forecastFlow = []
    }
    // 对预报流量进行赋值 显示到图表中
  },
  {
    immediate: true,
    deep: true
  }
)
watch(
  () => {
    props.servers
  },
  () => {
    // emitter.emit('clearEcharts')
    state.options.series = []
    state.options.legend[0].data = [
      {
        name: '预报时间',
        itemStyle: { opacity: 0 }
      },
      {
        name: '警戒水位',
        itemStyle: { opacity: 0 }
      },
      {
        name: '实测水位',
        itemStyle: { opacity: 0 }
      },
      {
        name: '实测流量',
        itemStyle: { opacity: 0 }
      },
      '降雨量'
    ]
    state.options.legend[1].data = []

    //时间集合
    let timeArr = []
    //预报水位集合
    let preWaterwArr = []
    //实测水位集合
    let realWaterArr = []
    //预报流量集合
    let preFlowArr = []
    //实测流量集合
    let realFlowArr = []
    //降雨量集合
    let rainArr = []
    //
    let timeFilter = []
    let preWaterwFilter = []
    let realFlowFilter = []
    let realWaterFilter = []
    let rainFilter = []
    let preFlowFilter = []
    if (props.servers.length) {
      if (props.servers.length == 1) {
        props.servers[0].ccResult.forEach((item) => {
          timeArr.push(item.tm)
          preWaterwArr.push(item.fz)
          realWaterArr.push(item.rz)
          preFlowArr.push(item.fq)
          realFlowArr.push(item.rq)
          rainArr.push(item.fp)
        })
        timeArr = [timeArr]
        preWaterwArr = [preWaterwArr]
        realWaterArr = [realWaterArr]
        preFlowArr = [preFlowArr]
        realFlowArr = [realFlowArr]
        rainArr = [rainArr]
        console.log(rainArr[0], '666')
      } else {
        props.servers.forEach((e, eIndex) => {
          // let arr = [e.tm,e.]
          if (e.ccResult.length) {
            timeFilter = e.ccResult.map((child, childIndex) => {
              return child.tm
            })
            preWaterwFilter = e.ccResult.map((child, childIndex) => {
              return child.fz
            })
            realWaterFilter = e.ccResult.map((child, childIndex) => {
              return child.rz
            })
            preFlowFilter = e.ccResult.map((child, childIndex) => {
              return child.fq
            })
            realFlowFilter = e.ccResult.map((child, childIndex) => {
              return child.rq
            })
            rainFilter = e.ccResult.map((child, childIndex) => {
              return child.fp
            })
          }

          timeArr.push(timeFilter)
          preWaterwArr.push(preWaterwFilter)
          realWaterArr.push(realWaterFilter)
          preFlowArr.push(preFlowFilter)
          realFlowArr.push(realFlowFilter)
          rainArr.push(rainFilter)
        })
      }
      if (state.forecastTime?.length) {
        state.forecastTime.forEach((t) => {
          if (!timeArr?.includes(t)) {
            timeArr[0].push(t)
          }
        })
      }
      //一种方案对比
      if (props.servers.length == 1) {
        state.options.xAxis[0].data = timeArr[0]
        state.options.xAxis[1].data = timeArr[0]
        state.options.legend[1].data.push(
          {
            name: '预报水位',
            itemStyle: { opacity: 0 }
          },
          {
            name: '预报流量',
            itemStyle: { opacity: 0 }
          }
        )
        state.options.series.push(
          {
            type: 'line',
            symbolSize: 0,
            name: '预报水位',
            lineStyle: {
              type: 'dashed',
              color: '#B22222'
            },
            itemStyle: {
              color: '#B22222'
            },
            showSymbol: false,
            xAxisIndex: 1,
            yAxisIndex: 1,
            smooth: true,
            data: preWaterwArr[0]
          },
          {
            type: 'line',
            symbolSize: 0,
            name: '预报流量',
            lineStyle: {
              type: 'dashed',
              color: '#009ACD'
            },
            itemStyle: {
              color: '#009ACD'
            },
            smooth: true,
            // symbol: 'circle',
            showSymbol: false,
            xAxisIndex: 1,
            yAxisIndex: 0,
            data: preFlowArr[0]
          }
        )
      }
      //添加预报时间、警戒水位、警戒流量
      state.options.series.push(
        {
          type: 'line',
          name: '预报时间',
          xAxisIndex: 1,
          yAxisIndex: 1,
          lineStyle: {
            // opacity: 0,
            type: 'dashed',
            color: '#dc143c'
          },
          markLine: {
            symbol: 'none', // 去掉标线最后面的箭头
            data: [
              {
                silent: false, // 鼠标悬停事件  true没有，false有
                lineStyle: {
                  type: 'dashed',
                  color: '#dc143c'
                },
                name: '预报时间',
                xAxis: props.servers[0].fcTime,
                // xAxis: '2023-06-03 04:00:00',
                label: {
                  formatter: function (v) {
                    return v.name + '：' + v.value
                  }
                }
              }
            ]
          }
        },
        {
          type: 'line',
          lineStyle: {
            // opacity: 0,
            color: '#FF0000'
          },
          tooltip: {
            show: true
          },
          symbolSize: 0,
          name: '警戒水位',
          xAxisIndex: 1,
          yAxisIndex: 1,
          // id: 'warningLine',
          data: [props.servers[0].warnInfo.wrz || ''],
          markLine: {
            symbol: 'none', // 去掉标线最后面的箭头
            label: {
              distance: [200, 30],
              position: 'insideMiddle', // start middle end
              formatter: function (v) {
                return v.name + '：' + v.value
              }
            },
            data: [
              {
                silent: false, // 鼠标悬停事件  true没有，false有
                lineStyle: {
                  type: 'solid',
                  color: '#FF0000'
                },
                name: '警戒水位',
                yAxis: props.servers[0].warnInfo.wrz || ''
              }
            ]
          }
        },

        {
          type: 'line',
          symbolSize: 0,
          name: '实测水位',
          lineStyle: {
            type: 'dashed',
            color: 'green'
          },
          itemStyle: {
            color: 'green'
          },
          smooth: true,
          showSymbol: false,
          xAxisIndex: 1,
          yAxisIndex: 1,
          data: realWaterArr[0]
        },
        {
          type: 'line',
          symbolSize: 0,
          name: '实测流量',
          lineStyle: {
            // type: 'solid'
          },
          smooth: true,
          symbol: 'circle',
          showSymbol: false,
          xAxisIndex: 1,
          yAxisIndex: 0,
          data: realFlowArr[0]
        },
        {
          type: 'line',
          symbolSize: 0,
          name: '预报流量',
          lineStyle: {
            // type: 'solid'
            color: '#3cf40bff'
          },
          smooth: true,
          symbol: 'circle',
          showSymbol: false,
          xAxisIndex: 1,
          yAxisIndex: 0,
          data: state.forecastFlow || ''
        },
        {
          name: '降雨量',
          type: 'bar',
          barWidth: '20%',
          barGap: '-100%',
          smooth: true,
          xAxisIndex: 0,
          yAxisIndex: 2,
          stack: '降雨量',
          data: rainArr[0],
          // data:[12,12323,23,213,123],
          itemStyle: {
            color: 'blue'
          },
          min: 0
        }
      )
      //多种方案对比
      if (props.servers.length > 1) {
        // let newArr = props.servers[0].result
        props.servers.forEach((child, childIndex) => {
          state.options.xAxis[0].data = timeArr[childIndex]
          state.options.xAxis[1].data = timeArr[childIndex]
          state.options.series.push(
            {
              type: 'line',
              symbolSize: 0,
              name: child.scName + ':',
              lineStyle: {
                // type: 'dashed',
                // color: '#F22E2E'
              },
              xAxisIndex: 1,
              yAxisIndex: 1,
              smooth: true,
              data: []
            },
            {
              type: 'line',

              name: '预报水位' + childIndex,

              lineStyle: {
                type: 'dashed',
                color: '#B22222'
              },
              itemStyle: {
                color: '#B22222'
              },
              symbolSize: 7,
              symbol: `path://${state.symbolsArr[childIndex]}`,
              showSymbol: childIndex == 0 ? false : true,
              xAxisIndex: 1,
              yAxisIndex: 1,
              smooth: true,
              data: preWaterwArr[childIndex]
            },
            {
              type: 'line',

              name: '预报流量' + childIndex,
              lineStyle: {
                type: 'dashed',
                color: '#009ACD'
              },
              itemStyle: {
                color: '#009ACD'
              },
              symbol: `path://${state.symbolsArr[childIndex]}`,
              showSymbol: childIndex == 0 ? false : true,
              symbolSize: 7,
              smooth: true,

              xAxisIndex: 1,
              yAxisIndex: 0,
              data: preFlowArr[childIndex]
            }
            // {
            //   type: 'line',
            //   symbolSize: 0,
            //   name: '实测水位' + childIndex,
            //   lineStyle: {
            //     type: 'dashed',
            //     color: 'green'
            //   },
            //   itemStyle: {
            //     color: 'green'
            //   },
            //   smooth: true,
            //   showSymbol: false,
            //   xAxisIndex: 1,
            //   yAxisIndex: 1,
            //   data: realWaterArr[childIndex]
            // },
            // {
            //   type: 'line',
            //   symbolSize: 0,
            //   name: '实测流量' + childIndex,
            //   lineStyle: {
            //     // type: 'solid'
            //   },
            //   smooth: true,
            //   symbol: 'circle',
            //   showSymbol: false,
            //   xAxisIndex: 1,
            //   yAxisIndex: 0,
            //   data: realFlowArr[childIndex]
            // },
            // {
            //   name: '降雨量' + childIndex,
            //   type: 'bar',
            //   barWidth: '20%',
            //   barGap: '-100%',
            //   smooth: true,
            //   xAxisIndex: 0,
            //   yAxisIndex: 2,
            //   stack: '降雨量',
            //   data: rainArr[childIndex],
            //   itemStyle: {
            //     color: 'blue'
            //   },
            //   min: 0
            // }
          )
          state.options.legend[1].data.push(
            {
              name: child.scName + ':',
              icon: 'none'
            },
            {
              name: '预报水位' + childIndex,
              itemStyle: childIndex == 0 ? { opacity: 0 } : ''
            },
            {
              name: '预报流量' + childIndex,
              itemStyle: childIndex == 0 ? { opacity: 0 } : ''
            }
            // {
            //   name: '实测水位' + childIndex,
            //   itemStyle: { opacity: 0 }
            // },
            // {
            //   name: '实测流量' + childIndex,
            //   itemStyle: { opacity: 0 }
            // },
            // '降雨量' + childIndex
          )
        })
      }
    } else {
      timeArr = []
      // emitter.emit('clearEcharts')
      state.options.series = []
      state.options.legend[0].data = [
        {
          name: '预报时间',
          itemStyle: { opacity: 0 }
        },
        {
          name: '警戒水位',
          itemStyle: { opacity: 0 }
        }
      ]
      state.options.legend[1].data = []
    }
  },
  {
    deep: true,
    immediate: true
  }
)
</script>

<style lang="less" scoped>
.line-echart {
  height: 100%;
}
.chartsMax {
  background: #f2f2f2;
}
</style>
